package org.jeecg.modules.demo.periodicwork.service.impl;

import org.jeecg.modules.demo.periodicwork.entity.PeriodicWork;
import org.jeecg.modules.demo.periodicwork.entity.PeriodicWorkCoopdept;
import org.jeecg.modules.demo.periodicwork.mapper.PeriodicWorkCoopdeptMapper;
import org.jeecg.modules.demo.periodicwork.mapper.PeriodicWorkMapper;
import org.jeecg.modules.demo.periodicwork.service.IPeriodicWorkService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 周期性工作
 * @Author: jeecg-boot
 * @Date:   2025-09-01
 * @Version: V1.0
 */
@Service
public class PeriodicWorkServiceImpl extends ServiceImpl<PeriodicWorkMapper, PeriodicWork> implements IPeriodicWorkService {

	@Autowired
	private PeriodicWorkMapper periodicWorkMapper;
	@Autowired
	private PeriodicWorkCoopdeptMapper periodicWorkCoopdeptMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(PeriodicWork periodicWork, List<PeriodicWorkCoopdept> periodicWorkCoopdeptList) {
		periodicWorkMapper.insert(periodicWork);
		if(periodicWorkCoopdeptList!=null && periodicWorkCoopdeptList.size()>0) {
			for(PeriodicWorkCoopdept entity:periodicWorkCoopdeptList) {
				//外键设置
				entity.setMainId(periodicWork.getId());
				periodicWorkCoopdeptMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(PeriodicWork periodicWork,List<PeriodicWorkCoopdept> periodicWorkCoopdeptList) {
		periodicWorkMapper.updateById(periodicWork);
		
		//1.先删除子表数据
		periodicWorkCoopdeptMapper.deleteByMainId(periodicWork.getId());
		
		//2.子表数据重新插入
		if(periodicWorkCoopdeptList!=null && periodicWorkCoopdeptList.size()>0) {
			for(PeriodicWorkCoopdept entity:periodicWorkCoopdeptList) {
				//外键设置
				entity.setMainId(periodicWork.getId());
				periodicWorkCoopdeptMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		periodicWorkCoopdeptMapper.deleteByMainId(id);
		periodicWorkMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			periodicWorkCoopdeptMapper.deleteByMainId(id.toString());
			periodicWorkMapper.deleteById(id);
		}
	}
	
}
